/*
 */
package com.muse.reflect;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * https://mapstruct.org/
 *
 * @author muse
 */
public class BeanUtils {
    public static void convertor(Object originObj, Object targetObj) throws Throwable {
        /** 1：获得class对象 */
        Class orginClazz = originObj.getClass();
        Class targetClazz = targetObj.getClass();

        /** 2：缓存originObj对象中的Field */
        Map<String, Field> fieldCache = new HashMap<>();
        Field[] orginFields = orginClazz.getDeclaredFields();
        for (Field field : orginFields) fieldCache.put(field.getName(), field);

        /** 3：赋值操作 */
        for (Field targetField : targetClazz.getDeclaredFields()) {
            if (!fieldCache.containsKey(targetField.getName())) continue;

            Field originField = fieldCache.get(targetField.getName());
            originField.setAccessible(true);
            targetField.setAccessible(true);
            targetField.set(targetObj, originField.get(originObj));
        }
    }

    public static void main(String[] args) throws Throwable{
        Person person = new Person("bob", 10, (byte)1, true);
        Robot robot = new Robot();

        /** 执行bean赋值操作 */
        BeanUtils.convertor(person, robot);

        System.out.println("person=" + person);
        System.out.println("robot=" + robot);
    }
}


